package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.admin.captcha.CustomArithmeticCaptcha;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import jakarta.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.awt.*;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo getCaptcha(){
        CustomArithmeticCaptcha specCaptcha = new CustomArithmeticCaptcha(130,48,4);
        //specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        //转为小写存入redis
        String code = specCaptcha.text();//.toLowerCase();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        String image = specCaptcha.toBase64();
        //将key code存入redis 并设置保留时间为60S
        stringRedisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        return new CaptchaVo(image,key);
    }

    /**
     * 登录校验
     * @param loginVo 包含用户名 密码 验证码key 验证码code
     * @return token
     */
    @Override
    public String login(LoginVo loginVo) {
        //1.先判断是否输入了验证码
        if(!StringUtils.hasText(loginVo.getCaptchaCode()))
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        //2.在redis中查询保存的code,若查询为空,则直接响应 验证码已过期
        String code = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if(code == null)
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        //3.比较redis中key对应的code与传输数据的code是否相同,不相同响应 验证码不正确
        if(!code.equals(loginVo.getCaptchaCode().toLowerCase()))
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        //4.根据username查询数据库 若不存在 响应账号不存在
        LambdaQueryWrapper<SystemUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserMapper.selectOne(userLambdaQueryWrapper);
        if(systemUser == null)
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        //5.查看用户状态 若被禁用 响应账号被禁
        if(systemUser.getStatus().equals(BaseStatus.DISABLE))
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        //6.比对传输的密码与数据库中的password是否一致 不一致则响应账号或密码错误
        if(!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword())))
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        //7.创建JWT 响应到浏览器
        return JwtUtil.createToken(systemUser.getId(),systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo getSystemUserInfoById(Long userId) {
        SystemUser systemUser = systemUserMapper.selectById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
